#!/usr/bin/env python
import ok
from struct import *
import time

xem = ok.FrontPanel()
if (xem.OpenBySerial('') != 0):
    raise RuntimeError, 'Failed to open USB connection.'

PLL = ok.PLL22150()
xem.GetPLL22150Configuration(PLL)
PLL.SetVCOParameters(400,48)
PLL.SetOutputSource(0,2)
PLL.SetOutputEnable(0,2)
PLL.SetDiv1(1,10)
xem.SetPLL22150Configuration(PLL)

if (xem.ConfigureFPGA(r'/mnt/work/projects/fpga/test2/toplevel.bit') != 0):
    raise RuntimeError, 'Failed to upload bit file to fpga.'    


data_out = ""

ctrl_state=0
ctrl_ram=0

def reset_w_addr():
	xem.ActivateTriggerIn( 83, 0 )

def write_t_data0( ):
	print "Writing t_data0"
	reset_w_addr()
	select_RAM( 2 )
	select_MODE( 1)
	ep_addr=156
	written = 0
	for i in range(0, 512):
		written += xem.WriteToPipeIn( ep_addr, pack( 'h',5) )
		written += xem.WriteToPipeIn( ep_addr, pack( 'h',100) )
	select_MODE(0)
	select_RAM(0)
	print written, "bytes or ", written/2, "shorts written to t_data0"
	return written

def write_t_data1( ):	#influences data0
	print "Writing t_data1"
	reset_w_addr()
	select_RAM( 3 )
	select_MODE( 1)
	ep_addr=156
	written = 0
	for i in range(0, 512):
		written += xem.WriteToPipeIn( ep_addr, pack( 'h',5) )  
		written += xem.WriteToPipeIn( ep_addr, pack( 'h',100))  
	select_MODE(0)
	select_RAM(0)
	print written, "bytes or ", written/2, "shorts written to t_data1"
	return written

def write_data0( ):
	print "Writing data0"
	reset_w_addr()
	select_RAM( 0 )
	select_MODE( 1 )
	ep_addr=156
	written = 0
	for i in range(0, 512):
		written += xem.WriteToPipeIn( ep_addr, pack( 'h',1) )
		written += xem.WriteToPipeIn( ep_addr, pack( 'h',1) )
	select_MODE(0)
	select_RAM(0)
	print written, "bytes or ", written/2, "shorts written to data0"
	return written

def write_data1( ):
	print "Writing data1"
	reset_w_addr()
	select_RAM( 1 )
	select_MODE( 1 ) 
	ep_addr=156
	written = 0
	for i in range(0, 512):
		written += xem.WriteToPipeIn( ep_addr, pack( 'h',0) ) #data1
		written += xem.WriteToPipeIn( ep_addr, pack( 'h',1) )
	select_MODE(0)
	select_RAM(0)
	print written, "bytes or ", written/2, "shorts written to data1"
	return written

	 
def select_RAM( ram):
	global ctrl_ram
	ep = 0
	if(ram == 0 ):					#data0
		ctrl_ram = 0
	elif( ram == 1):				#data1
		ctrl_ram = 4
	elif( ram == 2):				#t_data0
		ctrl_ram = 8
	elif( ram == 3):				#t_data1
		ctrl_ram = 12
	xem.SetWireInValue( ep, ctrl_state+ctrl_ram )
	print "Setting WireInValue", ctrl_state+ctrl_ram
	xem.UpdateWireIns()

def select_MODE( mode):
	global ctrl_state
	ep = 0
	if( mode == 0 ):				#stop
		ctrl_state = 0
	elif( mode == 1):				#load
		ctrl_state = 1
	elif( mode == 2):				#start
		ctrl_state = 2
	elif( mode == 3):				#unused
		ctrl_state = 3
	xem.SetWireInValue( ep, ctrl_state+ctrl_ram )
	print "Setting WireInValue", ctrl_state+ctrl_ram
	xem.UpdateWireIns()


data0 = write_data0( )
data1 = write_data1( ) 
t_data0 = write_t_data0( ) 
t_data1 = write_t_data1( )
select_MODE( 2 )
